package com.llkj.qingnianguoxue;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.jm.call.JMRtcClientManager;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.EventChangeUserBean;
import com.llkj.qingnianguoxue.book.BookFragment;
import com.llkj.qingnianguoxue.circle.CircleFragment;
import com.llkj.qingnianguoxue.home.HomeFragment;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.login.LoginActivity;
import com.llkj.qingnianguoxue.mine.MineFragment;
import com.llkj.qingnianguoxue.mine.ShopCartActivity;
import com.llkj.qingnianguoxue.util.AppManager;
import com.llkj.qingnianguoxue.util.JGuangUtil;
import com.llkj.qingnianguoxue.util.LocationUtil;
import com.llkj.qingnianguoxue.util.NetworkUtils;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.view.ChatView;
import com.llkj.qingnianguoxue.zhuanlan.ZhuanLanFragment;
import com.orhanobut.logger.Logger;
import com.tbruyelle.rxpermissions.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import rx.functions.Action1;

import static com.llkj.qingnianguoxue.home.JingXuanActivity.REQUEST_CART_CODE;


public class MainActivity extends BaseActivity implements View.OnClickListener {
    public final static String NOTIFICATION_MESSAGE = "notification_message";
    private long firstTime;//双击退出
    private FrameLayout flRootView;
    private RelativeLayout rlTabView;
    private LinearLayout llTab1, llTab2, llTab3, llTab4, llTab5;//底部导航
    private TextView tvNewMe;//个人中心红点
    private HomeFragment homeFragment;
    private CircleFragment circleFragment;
    private BookFragment bookFragment;
    private ZhuanLanFragment zhuanLanFragment;
    private MineFragment mineFragment;
    private MessageBroadcast mMessageBroadcast;
    ChatView ivCar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        systemBarTintManager.setStatusBarTintResource(R.color.colorFE4A49);

        new RxPermissions(this)
                .request(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CALL_PHONE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        if(aBoolean){
                            Location location = LocationUtil.getNetworkLocation(MainActivity.this);
                            boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
                            if(location!=null && isLogin){
                                Log.e("Log",location.getLatitude()+";"+location.getLongitude());
                                HttpMethod.updatePosition(MainActivity.this,MainActivity.this,
                                        String.valueOf(location.getLongitude()),String.valueOf(location.getLatitude()));
                            }
                        }
                    }
                });

        JMRtcClientManager.getJMRtcClientManager().initEngine(this);
        initView();
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,flRootView,R.color.colorFE4A49);
        EventBus.getDefault().register(this);

        initListener();

        setSelection(0);

        mMessageBroadcast = new MessageBroadcast();
        IntentFilter filter = new IntentFilter();
        filter.addAction(NOTIFICATION_MESSAGE);
        registerReceiver(mMessageBroadcast,filter);

    }

    private void initView() {
        ivCar = new ChatView(this);
        flRootView = (FrameLayout) findViewById(R.id.content_layout);
        rlTabView = (RelativeLayout) findViewById(R.id.tab_layout);
        llTab1 = (LinearLayout) findViewById(R.id.ll_tab1);
        llTab2 = (LinearLayout) findViewById(R.id.ll_tab2);
        llTab3 = (LinearLayout) findViewById(R.id.ll_tab3);
        llTab4 = (LinearLayout) findViewById(R.id.ll_tab4);
        llTab5 = (LinearLayout) findViewById(R.id.ll_tab5);
        tvNewMe = (TextView) findViewById(R.id.tv_new_me);
    }

    private void initListener() {
        llTab1.setOnClickListener(this);
        llTab2.setOnClickListener(this);
        llTab3.setOnClickListener(this);
        llTab4.setOnClickListener(this);
        llTab5.setOnClickListener(this);
        ivCar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
                if (!isLogin) {
                    dialogConfirm(null, null, null, null).show();
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString("need_result", "1");
                startActivityForResult(ShopCartActivity.class, bundle, REQUEST_CART_CODE);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeUser(EventChangeUserBean event){
        setJPushAlias();
    }

    @Override
    public void onClick(View v) {
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        switch (v.getId()) {
            case R.id.ll_tab1:
                setSelection(0);
                break;
            case R.id.ll_tab2:
                setSelection(1);
                break;
            case R.id.ll_tab3:
                setSelection(2);
                break;
            case R.id.ll_tab4:
                setSelection(3);
                break;
            case R.id.ll_tab5:
                setSelection(4);
                break;
        }
    }

    private void setSelection(int index) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        hideFragment(fragmentTransaction);
        hideIvCar();
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        switch (index) {
            case 0://
                setSelected(llTab1);
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                    Bundle bundle = new Bundle();
                    homeFragment.setArguments(bundle);

                    fragmentTransaction.add(R.id.content_layout, homeFragment, "tab1");
                } else {
                    fragmentTransaction.show(homeFragment);
                }
                fragmentTransaction.commit();
                showIvCar();
                break;
            case 1://
                setSelected(llTab2);
                if (circleFragment == null) {
                    circleFragment = new CircleFragment();
                    Bundle bundle = new Bundle();
                    circleFragment.setArguments(bundle);

                    fragmentTransaction.add(R.id.content_layout, circleFragment, "tab2");
                } else {
                    fragmentTransaction.show(circleFragment);
                }

                fragmentTransaction.commit();
                break;
            case 2://
                setSelected(llTab3);
                if (zhuanLanFragment == null) {
                    zhuanLanFragment = new ZhuanLanFragment();
                    Bundle bundle = new Bundle();
                    zhuanLanFragment.setArguments(bundle);

                    fragmentTransaction.add(R.id.content_layout, zhuanLanFragment, "tab4");
                } else {
                    fragmentTransaction.show(zhuanLanFragment);
                }
                fragmentTransaction.commit();
                break;
            case 3://
                if (!isLogin) {
                    dialogConfirm(null, null, null, null).show();
                    return;
                }
                setSelected(llTab4);
                if (bookFragment == null) {
                    bookFragment = new BookFragment();
                    Bundle bundle = getIntent().getExtras();
                    if (bundle != null) {
                        bookFragment.setArguments(bundle);
                    }

                    fragmentTransaction.add(R.id.content_layout, bookFragment, "tab3");
                } else {
                    fragmentTransaction.show(bookFragment);
                }
                fragmentTransaction.commit();
                break;
            case 4://
                if (!isLogin) {
                    dialogConfirm(null, null, null, null).show();
                    return;
                }
                tvNewMe.setVisibility(View.INVISIBLE);
                setSelected(llTab5);
                if (mineFragment == null) {
                    mineFragment = new MineFragment();
                    Bundle bundle = new Bundle();
                    mineFragment.setArguments(bundle);

                    fragmentTransaction.add(R.id.content_layout, mineFragment, "tab5");
                } else {
                    fragmentTransaction.show(mineFragment);
                }
                fragmentTransaction.commit();
                break;
        }

    }

    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        startActivity(LoginActivity.class);
    }

    private void setSelected(View view) {
        llTab1.setSelected(false);
        llTab2.setSelected(false);
        llTab3.setSelected(false);
        llTab4.setSelected(false);
        llTab5.setSelected(false);
        view.setSelected(true);
    }

    /**
     * 隐藏所有的fragment
     *
     * @param transaction
     */
    private void hideFragment(FragmentTransaction transaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }
        if (circleFragment != null) {
            transaction.hide(circleFragment);
        }
        if (bookFragment != null) {
            transaction.hide(bookFragment);
        }
        if (zhuanLanFragment != null) {
            transaction.hide(zhuanLanFragment);
        }
        if (mineFragment != null) {
            transaction.hide(mineFragment);
        }
    }

    public void setSelect(int position) {
        setSelection(position);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ivCar.destory();
        try {
            unregisterReceiver(mMessageBroadcast);
        } catch (Exception e) {
            e.printStackTrace();
        }
        EventBus.getDefault().unregister(this);
    }
    public void hideIvCar() {
        if (null!=ivCar && ivCar.isShown()) {
            ivCar.hide();
        }
    }

    public void showIvCar() {
        if (null!=ivCar && !ivCar.isShown()) {
            ivCar.show();
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - firstTime < 2 * 1000) {
                AppManager.getInstance().finishAllActivityAndExit();
                finish();
            } else {
                firstTime = System.currentTimeMillis();
                ToastUtil.makeLongText(this, "再次点击退出程序");
            }
        }
        return false;
    }

    /**
     * 首页接口调用，需要判断当前用户没有被其它设备登录
     */
    public void setJPushAlias(){
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        if(isLogin){
            String alias = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_ID);
            //调用JPush API设置Alias
            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
        }
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Logger.e("Log", logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Logger.e("Log", logs);
                    if (NetworkUtils.isNetworkConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, tags), 1000 * 60);
                    } else {
                        Logger.e("Log", "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Logger.e("Log", logs);
            }

        }

    };

    private static final int MSG_SET_ALIAS = 1001;

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Logger.e("Log", "Set alias in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;

                default:
                    Logger.e("Log", "Unhandled msg - " + msg.what);
            }
        }
    };

    public class MessageBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            tvNewMe.setVisibility(View.VISIBLE);
            if(intent.hasExtra("msg_data") && "1".equals(intent.getStringExtra("msg_data"))){
                int num = MyApplication.getInstance().sputil.getInt(ConstantUserInfo.IS_NEW_SYS_MSG)+1;
                MyApplication.getInstance().sputil.put(ConstantUserInfo.IS_NEW_SYS_MSG, num);
            }
            if (mineFragment != null) {
                mineFragment.setNewMsgVisible();
                tvNewMe.setVisibility(View.VISIBLE);
            }
        }
    }
    public void setNewMsgVisible(){
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        if(!isLogin){
            return;
        }
        String mUserId = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_ID);
        int num = MyApplication.getInstance().sputil.getInt(ConstantUserInfo.IS_NEW_SYS_MSG);
        boolean istrue = num>0?true:false;
        if(istrue){
            tvNewMe.setVisibility(View.VISIBLE);
        }else{
            tvNewMe.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setNewMsgVisible();
        JMRtcClientManager.getJMRtcClientManager().onResume();
    }
}
